/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AdminPedReposicion.java
 *
 * Created on Mar 11, 2011, 4:56:43 PM
 */

package administrador;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import javax.swing.table.*;


/**
 *
 * @author daniel1.Silva
 */
public class AdminPedReposicion extends javax.swing.JPanel {
    javax.swing.JTable tabla;
    JScrollPane js;
    Conexion conexion;
    int bodega;
    Usuario user;

    /** Creates new form AdminPedReposicion */
    public AdminPedReposicion(Conexion cEnt,int bodegaEnt,Usuario uEnt) {
        conexion=cEnt;
        bodega=bodegaEnt;
        user=uEnt;

        initComponents();
        muestroPedidos();
    }

    public void muestroPedidos(){
        ResultSet respuesta=conexion.consultarBase("SELECT codigo,fecha,bodega,observacion FROM `bdmultiadmin`.`ped_reposicion` group by codigo; ");
     //Obtengo Filas-Arreglo de Titulos de Columnas
        int filas=conexion.obtenerFilas(respuesta);
        String[] titulosCol=conexion.obtenerColumnas(respuesta);

        //Creo la tabla:

        CrearTabla(filas,titulosCol);
        llenaTabla(respuesta,titulosCol.length,filas);
    }


     public void CrearTabla(int filas,String[] titulos){

        int columnas=titulos.length;
        String[][] tabla0=new String[filas][columnas];

        tabla= new JTable(tabla0,titulos);

        //Aqui le especifico para que la tabla acepte valores doubles e int:
        //--------------------------------------------------------------------
        final boolean[] canEdit = new boolean [columnas];
        for(int p=0;p<columnas;p++){
        canEdit[p]=false;
        }
        tabla.setModel(new javax.swing.table.DefaultTableModel(
            tabla0,titulos
        ) {
           // boolean[] canEdit = new boolean [] { false, false, false, false};

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        //---------------------------------------------------------------------

        //Le doy el evento del LCick del Mouse:
        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaMouseClicked(evt);
            }
        });

        //remuevo el JScroll para que no se monte cuando cree el nuevo:
        //*************************************************************
        try{
        this.remove(js);
        }catch(java.lang.NullPointerException e){}
        //*************************************************************

        //Pongo en la tabla:
            js = new JScrollPane(tabla);

            js.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(198, 196, 196)));
            js.setBounds(150, 80, 670, 400);
            js.setVisible(true);
            this.add(js);
            js.updateUI();
    }

     public void llenaTabla(ResultSet r,int columnas,int filas){
        try{
            r.beforeFirst();

            int j=0;
            while(r.next()) {

                for(int i=0;i<columnas;i++) {

                    Object toma=r.getObject(i+1);
                    //System.out.println("toma valor:"+toma+" * fila:"+j+" * column:"+i);
                    try{
                        tabla.setValueAt(toma,j,i);
                    }catch(java.lang.ArrayStoreException e){
                        System.out.print("Errrrorrr");
                        tabla.setValueAt("null",j,i);
                    }
                }

                j++;
            }
        }catch(SQLException sqle){
           //System.out.println("Error al mostrar los datos");
            System.err.println(sqle);
        }

    }


     private void tablaMouseClicked(java.awt.event.MouseEvent evt) {
    // Evento del click del mouse sobre la tabla:
         int fila=tabla.getSelectedRow();
        //System.out.println("Click en la Fila :"+fila);
      
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        bt_Nuevo = new javax.swing.JButton();
        bt_Modificar = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(administrador.AdministradorApp.class).getContext().getResourceMap(AdminPedReposicion.class);
        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        bt_Nuevo.setText(resourceMap.getString("bt_Nuevo.text")); // NOI18N
        bt_Nuevo.setName("bt_Nuevo"); // NOI18N
        bt_Nuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_NuevoActionPerformed(evt);
            }
        });

        bt_Modificar.setText(resourceMap.getString("bt_Modificar.text")); // NOI18N
        bt_Modificar.setName("bt_Modificar"); // NOI18N
        bt_Modificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_ModificarActionPerformed(evt);
            }
        });

        jButton4.setText(resourceMap.getString("jButton4.text")); // NOI18N
        jButton4.setName("jButton4"); // NOI18N
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jButton4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(bt_Nuevo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(bt_Modificar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE))
                .addContainerGap(449, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(11, 11, 11)
                .addComponent(bt_Nuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bt_Modificar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(231, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void bt_NuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_NuevoActionPerformed
        // TODO add your handling code here:
        NuevoPedido np=new NuevoPedido(conexion,bodega,user,this);
    }//GEN-LAST:event_bt_NuevoActionPerformed

    private void bt_ModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_ModificarActionPerformed
        // TODO add your handling code here:

        String fecha=new java.sql.Date(System.currentTimeMillis()).toString();
        //saco la fila seleccionada:
        int filas=tabla.getSelectedRow();
        String codigopedido=String.valueOf(tabla.getValueAt(filas,0));
        String bodegaMod=String.valueOf(tabla.getValueAt(filas,2));
        String observacion=String.valueOf(tabla.getValueAt(filas,3));


        //limpio el vector de productos y le pongo el del pedido:
        conexion.actualizarBase("update productosbodega set cant_pedida=0;");
        //pongo las cantidades de los productos del pedido:

        ResultSet resp= conexion.consultarBase("SELECT cod_producto,cantidad FROM itm_pedreposicion i where cod_pedido="+codigopedido+" and cantidad>0;");
        try {
            resp.beforeFirst();
            while(resp.next()){

                String codigop=resp.getString(1);
                int cantp=resp.getInt(2);

                boolean exito=conexion.actualizarBaseResp("update productosbodega set cant_pedida="+cantp+" where codigo like '"+codigop+"';");


                 if(exito){
                   // JOptionPane.showMessageDialog(this, "Se creo exitosamente la base bodega !!", "Informacion", JOptionPane.WARNING_MESSAGE);

                }else{
                    JOptionPane.showMessageDialog(this, "Se produjo un error en la creacion !!", "Informacion", JOptionPane.WARNING_MESSAGE);
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(AdminPedReposicion.class.getName()).log(Level.SEVERE, null, ex);
        }

        pedidoReposicion pr=new pedidoReposicion(conexion,bodegaMod,user,observacion,fecha,codigopedido);


    }//GEN-LAST:event_bt_ModificarActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:

        int opccion = 0;
        boolean exito1=false;
        boolean exito2=false;
        boolean exito3=false;
        boolean exito4=false;

        conexion.consultarBase("START TRANSACTION;");


        opccion = JOptionPane.showConfirmDialog(this, "Seguro Desea Eliminar este Pedido de Reposicion?", "Alerta", 0);
        if (opccion == 0) {
            int filas = tabla.getSelectedRow();
            String codigopedido = String.valueOf(tabla.getValueAt(filas, 0));

            //borro cabecera:
            exito1=conexion.actualizarBaseResp("delete from ped_reposicion where codigo=" + codigopedido + ";");

            //borro detalle:
            exito2=conexion.actualizarBaseResp("delete from itm_pedreposicion where cod_pedido=" + codigopedido + ";");


          String IPCliente ="174.136.152.21";// "174.136.152.21"Sexylocuras; 
          String nombre = "sexyusuario";//"daniel1";
          String password = "yxes1984";
          String dbcliente = "sexylocuras";//sexylocuras_mysql4608ff1c2ef2554b21b127617fc4e569554b21b127617fc4e569
          String puerto = "3306";


          //Realizo la conexion a la base de datos cliente:
          Conexion conexionWF = new Conexion();


           if (!conexionWF.conectarBase(nombre, password, puerto, dbcliente, IPCliente)) {
           

           }else{
          conexionWF.consultarBase("START TRANSACTION;");
          exito3=conexionWF.actualizarBaseResp("delete from ped_reposicion where codigo=" + codigopedido + ";");
          exito4=conexionWF.actualizarBaseResp("delete from itm_pedreposicion where cod_pedido=" + codigopedido + ";");
           }

           if(exito1&&exito2&&exito3&&exito4){
           conexion.consultarBase("COMMIT;");
           conexionWF.consultarBase("COMMIT;");
           }else{
           JOptionPane.showMessageDialog(this, "Se produjo un error en el borrado !!", "Informacion", JOptionPane.WARNING_MESSAGE);
           conexion.consultarBase("ROLLBACK;");
           conexionWF.consultarBase("ROLLBACK;");
           }
            try {
                conexionWF.cerrarConexion();
            } catch (Exception ex) {
                Logger.getLogger(AdminPedReposicion.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    muestroPedidos();



    }//GEN-LAST:event_jButton4ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bt_Modificar;
    private javax.swing.JButton bt_Nuevo;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables

}
